﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Collections;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Sunny.UI;
using CoreShop.Model;
using CoreShop.Library;
using SqlSugar.Extensions;
using Yitter.IdGenerator;
using Org.BouncyCastle.Asn1;

namespace CoreShop.App
{
    public partial class frmCouponPay : UIForm
    {
        private List<corecmsfoodordering> orderingDetail = null;
        public decimal mCouponPayAmt = 0;
        public string mCouponCode = "";
        public TiktokPostModel TiktokModel = null;

        public frmCouponPay(List<corecmsfoodordering> _orderingDetail, string dRealAmt, string code)
        {
            InitializeComponent();
            gridBalace.AutoGenerateColumns = false;
            orderingDetail = _orderingDetail;
            lblRealAmt.Text = dRealAmt;
            mCouponCode = code;
        }

        private void btn_Close_Click(object sender, EventArgs e)
        {
            mCouponPayAmt = 0;
            Close();
        }

        private void txt_code_Leave(object sender, EventArgs e)
        {
            //txtSendKey.Focus();
        }

        private void frmCouponPay_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 27) btn_Close_Click(null,null);
        }

        private void GetCouponDouyin() 
        {
            try
            {
                string url = "https://webapi.pos08.com:4433/api/tiktok/CertificatePrepare";
                JObject Jparams = new JObject();
                Jparams.Add(new JProperty("data", txtSendKey.Text));
                string result = HttpHelper.httpPost(url, Jparams.ToString());
                JObject retObj = JObject.Parse(result);
                string data = retObj["data"].ToString();
                TiktokModel = JsonConvert.DeserializeObject<TiktokPostModel>(data);
                if (TiktokModel.error_code != "0")
                {
                    MessageBox.Show("券不存在或无法使用。");
                    txtSendKey.Clear();
                    txtSendKey.Focus();
                    return;
                }
                BindData();
                List<corecmsfoodorderpayment> posPays = this.binDetail.DataSource as List<corecmsfoodorderpayment>;

                int index = 1;
                bool isExist = false;
                string sCode = "";
                foreach (var item in TiktokModel.certificates)
                {
                    isExist = false;
                    if (string.IsNullOrEmpty(item.sku.third_sku_id))
                    {
                        isExist = true;
                    }
                    else
                    {
                        foreach (var drSlaver in orderingDetail)
                        {
                           sCode = CommFunc.ConvertToString(drSlaver.number);
                           string[] Fields = item.sku.third_sku_id.Split(',');
                           for (int i = 0; i <= Fields.Length - 1; i++)
                           {
                               if (Fields[i].Trim().Equals(sCode)) isExist = true;
                           }
                        }
                    }

                    if (isExist)
                    {
                        var posPay = new corecmsfoodorderpayment();
                        posPay.id = index;
                        posPay.id = (long)YitIdHelper.NextId();//先给付值，方便删除行
                        posPay.orderId = 0;
                        posPay.paymentId = 0;
                        posPay.payName = item.sku.title;
                        posPay.paymentCode = item.encrypted_code;// sysPayment.code;
                        posPay.payAmount = item.sku.market_price / 100;// item.amount.coupon_pay_amount / 100;
                        posPay.takeAmount = item.sku.market_price / 100;// item.amount.coupon_pay_amount / 100;
                        posPay.status = 1;//先标记为未支付，如果移动支付等支付后改为已支付                        
                        if (index > 1) posPay.status = 0;
                        if (item.sku.groupon_type == 1) posPay.btnTitle = "团购券";
                        if (item.sku.groupon_type == 2) posPay.btnTitle = "代金券";
                        if (item.sku.groupon_type == 3) posPay.btnTitle = "次卡";
                        this.binDetail.Add(posPay);
                        index += 1;
                    }
                }
                if (posPays.Count == 0)
                {
                    MessageBox.Show("券不存在或无法使用。");
                    txtSendKey.Clear();
                    txtSendKey.Focus();
                    return;
                }
                var certificate = TiktokModel.certificates.First();
                lblName.Text = certificate.sku.title;
                lblAmount.Text = (certificate.amount.original_amount / 100).ToString("#0.00");
                lbl_MmbIntg.Text = "";
                if (certificate.sku.groupon_type == 1) lbl_MmbIntg.Text = "团购券";
                if (certificate.sku.groupon_type == 2) lbl_MmbIntg.Text = "代金券";
                if (certificate.sku.groupon_type == 3) lbl_MmbIntg.Text = "次卡";
                txtSendKey.Clear();
                txtSendKey.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
               

        private void txt_code_KeyDown(object sender, KeyEventArgs e)
        {
            
            if ((e.KeyCode == Keys.Enter) && (string.IsNullOrEmpty(mCouponCode)) && (!string.IsNullOrEmpty(txtSendKey.Text)))
            {
                //btn_CouponPay_Click(btn_CouponPay, null);
                GetCouponDouyin();
                e.Handled = true;   //将Handled设置为true，指示已经处理过KeyPress事件
                return;
            }

            //付款方式快揵键
            int mkeycode = e.KeyValue;//F1到F12,a-z这快捷键
            switch (mkeycode)
            {
                case 13:
                    if (txtSendKey.Text.Length == 0)
                    {
                        btn_CouponPay_Click(btn_CouponPay,null);
                    }
                    break;  
                case 116:
                    btnGetAll_Click(null,null);
                    break;
                case 27:
                    btn_Close_Click(null, null);
                    break; 
            }
        }

        
        private void btn_CouponPay_Click(object sender, EventArgs e)
        {
            if ((TiktokModel == null) || (TiktokModel.error_code != "0"))
            {
                lbl_msg1.Text = "提示：请扫核销券码!";
                txtSendKey.Focus();
                return;
            }
            List<corecmsfoodorderpayment> posPays = this.binDetail.DataSource as List<corecmsfoodorderpayment>;
            var drSel = posPays.Where(p => p.status == 1).ToList();
            if (drSel.Count < 1)
            {
                MessageBox.Show("请选择所要核销的券！");
                return;
            }

            var certificates = new string[drSel.Count];
            mCouponPayAmt = 0;
            int index = 0;
            foreach (var posPay in drSel)
            {
                certificates[index] = posPay.paymentCode;
                mCouponPayAmt += posPay.payAmount; 
                index += 1;             
            }
            try
            {
                var certificate = TiktokModel.certificates.First();
                string url = "https://webapi.pos08.com:4433/api/tiktok/CertificateVerify";
                JObject Jparams = new JObject();
                Jparams.Add(new JProperty("verify_token", TiktokModel.verify_token));                
                Jparams.Add(new JProperty("encrypted_codes", certificates));
                Jparams.Add(new JProperty("poi_id", AppConstVars.systemsetup.tiktokShopID));//6601142799414855694
                string result = HttpHelper.httpPost(url, Jparams.ToString());
                JObject retObj = JObject.Parse(result);
                string dataStr = retObj["data"].ToString();
                JObject dataObj = JObject.Parse(dataStr);
                string error_code = dataObj["error_code"].ToString();
                if (error_code != "0")
                {
                    MessageBox.Show("核销券失败。");
                    return;
                }
                string verify_results = dataObj["verify_results"].ToString();
                var VerifyResults = JsonConvert.DeserializeObject<List<VerifyResultModel>>(verify_results);

                foreach (var item in VerifyResults)
                {
                    if (item.result != 0)
                    {
                        MessageBox.Show(item.msg);
                        return;
                    }
                }
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void frmCouponPay_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(mCouponCode))
            {
                txtSendKey.Text = mCouponCode;
                GetCouponDouyin();
            }
        }

        private void BindData()
        {
            List<corecmsfoodorderpayment> lstPosPay = new List<corecmsfoodorderpayment>();
            this.binDetail.DataSource = lstPosPay;
            this.gridBalace.DataSource = this.binDetail;
        }

        private void btnGetAll_Click(object sender, EventArgs e)
        {
            List<corecmsfoodorderpayment> posPays = this.binDetail.DataSource as List<corecmsfoodorderpayment>;
            foreach (var posPay in posPays)
            {
                posPay.status = 1;
            }
            this.binDetail.DataSource = null;
            this.binDetail.DataSource = posPays;
            this.gridBalace.DataSource = this.binDetail;
        } 

    }
}
